# coding=utf-8

import logging
import python_library.webpy as web
from logging.handlers import RotatingFileHandler
from bind_worker import BindWoker


class BindService(object):
  """绑定服务器入口
     接受http请求并调用实际绑定实现类
  """

  # web路径对应处理类
  _URLS = ("/", "Index",
          "/match_album", "MatchAlbum",
          "/add_album", "AddAlbum",
          "/del_album", "DelAlbum",
          "/get_album_in_memary", "GetAlbumInMemary")

  def __init__(self):
    self._init_log()
    web.config.debug = False
    self.app = web.application(BindService._URLS, globals())
    self.worker = BindWoker()

  def _init_log(self):
    """初始化日志配置信息
    """
    log_level = logging.INFO
    #log_level = logging.DEBUG
    log_format = "[%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s"
    logging.basicConfig(level=log_level, format=log_format)
    handler = RotatingFileHandler("bind_service.log", maxBytes=100*1024*1024, backupCount=2)
    handler.setLevel(log_level)
    handler.setFormatter(logging.Formatter(log_format))
    logging.getLogger().addHandler(handler)


class Index(object):
  """处理类：根路径
  """

  def GET(self):
    return "usage: match_album, add_album, del_album"


class MatchAlbum(object):
  """处理类：绑定匹配
  """

  def GET(self):
    video_id = web.input(video_id=None).video_id
    if not video_id:
      return "Empty video_id"
    return worker.match(video_id)


class AddAlbum(object):
  """处理类：添加album
  """

  def GET(self):
    album_id = web.input(album_id=None).album_id
    return worker.add_album(album_id)


class DelAlbum(object):
  """处理类：删除album
  """

  def GET(self):
    params = web.input(album_id=None, video_type=None)
    return worker.del_album(params.album_id, params.video_type)


class GetAlbumInMemary(object):
  """处理类：得到内存中的album信息（用于debug）
  """

  def GET(self):
    params = web.input(album_id=None, video_type=None)
    return worker.get_album_in_memary(params.album_id, params.video_type)


if __name__ == "__main__":
  bindService = BindService()
  worker = bindService.worker
  bindService.app.run()
  # web.httpserver.runsimple(bindService.app.wsgifunc(), ("0.0.0.0", 8888))